<template>
    <div class="add-wrapper">

      <top-bar :title="topTitle"></top-bar>

      <div class="address-con">
        <h4 class="title">地址选择</h4>
        <p class="current-position"><span class="red-icon-position">*</span>当前定位</p>
        <div class="city" @click="choseCity">{{locationInfo}}</div>
        <div class="details-address">
          <x-input  v-model="form.nowDetail"  placeholder="输入具体地址" :show-clear="false"></x-input>
          <span class="red-icon">*</span>
        </div>
      </div>

      <div class="baby-info">
        <div class="bar-code">
          <x-input  v-model="form.name"  placeholder="输入婴儿姓名" :show-clear="false"></x-input>
          <span class="red-icon">*</span>
        </div>
        <div class="bar-code">
          <x-input  v-model="form.motherName"  placeholder="输入妈妈姓名" :show-clear="false"></x-input>
          <span class="red-icon">*</span>
        </div>
        <div class="bar-code">
          <x-input  v-model="form.fatherName"  placeholder="输入爸爸姓名" :show-clear="false"></x-input>
          <span class="red-icon"></span>
        </div>
        <div class="relation-select common-select">
          <popup-picker
            :data="relationList"
            v-model="relationValue"
            @on-change="relationChange"
            placeholder="选择同儿童的关系"></popup-picker>
          <span class="red-icon">*</span>
        </div>
        <div class="relation-select common-select">
          <popup-picker
            :data="sexList"
            v-model="sexValue"
            @on-change="sexChange"
            placeholder="选择儿童的性别"></popup-picker>
          <span class="red-icon">*</span>
        </div>
        <div class="datetime-select common-select">
          <datetime
            v-model="form.birthday"
            placeholder="选择儿童的生日"
            :end-date="today"
            ></datetime>
          <span class="red-icon">*</span>
        </div>
        <div class="bar-code common-select">
          <x-input v-model="form.serial"  class="weui-vcode" :show-clear="false" placeholder="输入接种本上儿童条码">
            <!--<x-button slot="right" type="primary" class="scan-btn" @click.native="scanBtn">点击扫描</x-button>-->
          </x-input>
        </div>
        <div class="upload-pic">
          <h4 class="title">上传照片</h4>
          <div class="upload-btn" v-bind:style="{backgroundImage: `url(${preImg})` }">
            <a v-show="!preImg">+</a>
            <p v-show="!preImg">添加照片</p>
            <input type="file" id="file" class="upImg"
                   accept="image/*"
                   @change="tirggerFile($event)" />
          </div>
        </div>

      </div>

      <div class="btn-wrapper">
        <x-button @click.native="submit">确定</x-button>
      </div>

      <popup v-model="popupShow" class="location-popup">
        <div>
          <div class="location-tab-nav">
            <a  :class="locationIndex==0?'active':''"  @click="province">省份</a>
            <a  :class="locationIndex==1?'active':''" @click="cityTab">城市</a>
            <a  :class="locationIndex==2?'active':''" @click="countryTab">区</a>
            <a  :class="locationIndex==3?'active':''" @click="townyTab">县</a>
            <a  :class="locationIndex==4?'active':''" @click="villageTab">乡</a>
            <a class="confirm-btn" @click="confirmC">确定</a>
          </div>
          <div class="location-con">
            <!--省份-->
            <ul v-show="locationIndex==0">
              <li v-for="(provinceItem,index) in provinceList"  :class="provinceIndex==index?'active':''"  @click="provinceChoose(provinceItem,index)" :key="index">{{provinceItem.name}}</li>
            </ul>
            <!--城市-->
            <ul v-show="locationIndex==1">
              <li v-for="(cityItem,index) in cityList"  :class="cityIndex==index?'active':''" @click="cityChoose(cityItem,index)" :key="index">{{cityItem.name}}</li>
            </ul>
            <!--区-->
            <ul v-show="locationIndex==2">
              <li v-for="(countryItem,index) in countryList" :class="countryIndex==index?'active':''" @click="countryChoose(countryItem,index)" :key="index">{{countryItem.name}}</li>
            </ul>
            <!--县-->
            <ul v-show="locationIndex==3">
              <li v-for="(townItem,index) in townList" :class="townIndex==index?'active':''" @click="townChoose(townItem,index)" :key="index">{{townItem.name}}</li>
            </ul>
            <!--乡-->
            <ul v-show="locationIndex==4">
              <li v-for="(villageItem,index) in villageList" :class="villageIndex==index?'active':''" @click="villageChoose(villageItem,index)"  :key="index">{{villageItem.name}}</li>
            </ul>
          </div>
        </div>
      </popup>

    </div>
</template>

<script>
  import Vue from 'vue';
  import axios from 'axios'
  import { XInput,XButton,PopupPicker,Datetime,Popup } from 'vux'
  Vue.prototype.$http = axios;
  import url from '../../../config/app.config'
  import TopBar from '@/components/top';
  import WechatPlugin from '@/utils/WechatPlugin';
  import $ from 'jquery';

    export default {
        name: "add",
        metaInfo () {
          return {
            title: '新增儿童信息'
          }
        },
        data(){
        return {
          topTitle:'新增儿童信息',
          relationValue:[],
          relationList: [['父亲', '母亲','爷爷','奶奶','外公','外婆','监护人','老师','其他']],
          sexList:[['男', '女']],
          sexValue:[],
          dataValue:'',

          popupShow:false,

          locationIndex:0,
          provinceList:[],
          provinceIndex:null,
          cityList:[],
          cityIndex:null,
          countryList:[],
          countryIndex:null,
          townList:[],
          townIndex:null,
          villageList:[],
          villageIndex:null,

          form:{
            userId:null,
            birthday:'',
            name:'',
            relationship:'',  // 同儿童关系
            nowDetail:'',  // 详细地址
            provinceId:null,  // 省份ID
            cityId:null,  // 城市Id
            countryId:null, // 区县ID
            townId:null,  // 乡镇ID
            villageId:null,  // 乡村ID
            sex:null,
            serial:'',
            motherName:'',  //母亲姓名
            fatherName:'',  //父亲姓名
          },
          userInfo:{},
          locationInfo:'',

          provinceName:'',
          cityName:'',
          countryName:'',
          townName:'',
          villageName:'',
          provinceId:null,
          cityId:null,
          countryId:null,
          townId:null,
          villageId:null,

          today:this.$moment().format('YYYY-MM-DD'),

          formData: new FormData(),
          preImg:'',

          weixXinData:{
            appId:'',
            nonceStr:'',
            sign:'',
            timestamp:''
          },

          id:'',
        }
      },
        mounted(){
          this.province();
          let that=this;
          this.userInfo=JSON.parse(sessionStorage.getItem('userInfo'));
          this.form.userId=this.userInfo.userId;
          this.id=this.$route.query.id

          if(this.$route.query.id){
              let children=JSON.parse(sessionStorage.getItem('children'));
              for(let i in children){
                if(this.$route.query.id==children[i].id){
                  if(children[i].name){
                    that.form.name=children[i].name;
                  }

                  if(children[i].sex){
                    that.form.sex=children[i].sex;
                  }

                  if(children[i].sex){
                    that.sexValue=[children[i].sex];
                  }

                  if(children[i].mother){
                    that.form.motherName=children[i].mother;
                  }

                  if(children[i].father){
                    that.form.fatherName=children[i].father;
                  }

                  if(children[i].nowDetail){
                    that.form.nowDetail=children[i].nowDetail;
                  }

                  if(children[i].serial){
                    that.form.serial=children[i].serial;
                  }

                  if(children[i].relationship){
                    that.relationValue=[children[i].relationship];
                    that.form.relationship=children[i].relationship;
                  }

                  this.$nextTick(function(){
                    if(children[i].birthday){
                      that.form.birthday=children[i].birthday;
                    }
                  })

                  if(children[i].babyPhoto){
                    this.preImg=url.http_url+children[i].babyPhoto;
                  }
                  this.form.userId=sessionStorage.getItem('userId')

                  this.form.provinceId=children[i].provinceId; // 省份ID
                  this.form.cityId=children[i].cityId; // 城市Id
                  this.form.countryId=children[i].countryId; // 区县ID
                  this.form.townId=children[i].townId; //乡镇ID
                  this.form.villageId=children[i].villageId  //乡村ID
                  this.province();
                  this.reverseCity();
                }
            }
          }

          this.getData();

        },
      computed:{
        submitDisabled(){
          let condition=this.form.nowDetail !=='' && this.form.name !==''
            && this.form.sex!==null && this.form.relationship!=='' && this.form.birthday!==''  && this.form.motherName!==''
          if(condition){
            return false
          }
          return true

        }
      },
       methods:{
         getData(){
           this.$api.get('/systemPick/getWeixinParams').then( (res)=> {
             if(res.data.result==0){
               this.weixXinData.appId=res.data.obj.appId;
               this.weixXinData.nonceStr=res.data.obj.nonceStr;
               this.weixXinData.sign=res.data.obj.sign;
               this.weixXinData.timestamp=res.data.obj.timestamp;
             }
           })
         },
         scanBtn(){
           let that=this;
           const wx_url = url.http_url_weixin;
           const urll = encodeURIComponent(window.location.href);
           const aurl = `${wx_url}/api/sign?nonceStr=${this.weixXinData.nonceStr}&timestamp=${this.weixXinData.timestamp}&url=${urll}`;

           $.ajax({
             url: aurl,
             success: function(res) {
               wx.config({
                 debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                 appId: that.weixXinData.appId, // 必填，公众号的唯一标识
                 timestamp: that.weixXinData.timestamp, // 必填，生成签名的时间戳
                 nonceStr:that.weixXinData.nonceStr, // 必填，生成签名的随机串
                 signature: res.signature, // 必填，签名，见附录1
                 jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline', 'onMenuShareQQ', 'onMenuShareQZone'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
               })
             }
           })
         },
         choseCity(){
            this.popupShow=true;
         },
         //初始化省份
         province(){
           this.locationIndex=0;
           this.$api.post('/systemPick/findAllCities',{
             type:'PROVINCE',
             parentId:'zh'
           }).then( (res)=> {
             this.provinceList=res.data.obj;

             if(this.id){
               this.provinceList.forEach(item=>{
                 if(item.id==this.form.provinceId){
                   this.provinceName=item.name;
                   this.locationInfo=this.provinceName;
                 }
               })
             }

           })
         },
         // 选择省
         provinceChoose(item,index){
           this.$api.post('/systemPick/findAllCities',{
             type:'CITY',
             parentId:item.id
           }).then( (res)=> {
             this.cityIndex=null;
             this.countryId=null;
             this.townId=null;
             this.villageId=null;
             this.cityName='';
             this.countryName='';
             this.townName='';
             this.villageName='';

             this.provinceIndex=index;
             this.provinceName=item.name;
             this.provinceId=item.id;

             if(res.data.obj.length>0){
               this.cityList=res.data.obj;
               this.locationIndex=1;
             }

           })
         },
         //选择城市
         cityChoose(item,index){
           this.$api.post('/systemPick/findAllCities',{
             type:'COUNTRY',
             parentId:item.id
           }).then( (res)=> {
             this.countryId=null;
             this.townId=null;
             this.villageId=null;
             this.countryName='';
             this.townName='';
             this.villageName='';

             this.cityIndex=index;
             this.cityName=item.name;
             this.cityId=item.id;

             if(res.data.obj.length>0){
               this.countryList=res.data.obj;
               this.locationIndex=2;
             }

           })
         },
         //区
         countryChoose(item,index){
           this.$api.post('/systemPick/findAllCities',{
             type:'TOWN',
             parentId:item.id
           }).then( (res)=> {
             if(res.data.obj.length>0){
               this.townId=null;
               this.villageId=null;
               this.townName='';
               this.villageName='';

               this.countryName=item.name;
               this.countryId=item.id;
               this.townList=res.data.obj;
               this.locationIndex=3;
               this.countryIndex=index;

             }
           })
         },
         //县
         townChoose(item,index){
           this.$api.post('/systemPick/findAllCities',{
             type:'VILLAGE',
             parentId:item.id
           }).then( (res)=> {
             this.villageId=null;
             this.villageName='';

             this.townName=item.name;
              this.townId=item.id;

             this.villageList=res.data.obj;
             this.locationIndex=4;
             this.townIndex=index;
           })
         },
         //乡
         villageChoose(item,index){
           this.villageName=item.name;
           this.villageId=item.id;
           this.villageIndex=index;

           /*this.locationInfo=this.provinceName+' '+this.cityName+' '+this.countryName+' '+this.townName+' '+item.name;
           this.popupShow=false;

           this.form.provinceId=this.provinceId;
           this.form.cityId=this.cityId;
           this.form.countryId=this.countryId;
           this.form.townId=this.townId;
           this.form.villageId=item.id;*/
         },
         confirmC(){
           if(this.provinceName){
              if(this.cityName){
                  if(this.countryName){
                      if(this.townName){
                          if(this.villageName){
                            this.form.provinceId=this.provinceId;
                            this.form.cityId=this.cityId;
                            this.form.countryId=this.countryId;
                            this.form.townId=this.townId;
                            this.form.villageId=this.villageId;
                            this.popupShow=false;
                            this.locationInfo=this.provinceName+' '+this.cityName+' '+this.countryName+' '+this.townName+' '+this.villageName;
                          }else{
                            this.form.provinceId=this.provinceId;
                            this.form.cityId=this.cityId;
                            this.form.countryId=this.countryId;
                            this.form.townId=this.townId;
                            this.locationInfo=this.provinceName+' '+this.cityName+' '+this.countryName+' '+this.townName;
                            this.popupShow=false;
                          }
                      }else{
                        this.form.provinceId=this.provinceId;
                        this.form.cityId=this.cityId;
                        this.form.countryId=this.countryId;
                        this.locationInfo=this.provinceName+' '+this.cityName+' '+this.countryName;
                        this.popupShow=false;
                      }
                  }else{
                    this.form.provinceId=this.provinceId;
                    this.form.cityId=this.cityId;
                    this.locationInfo=this.provinceName+' '+this.cityName;
                    this.popupShow=false;
                  }
              }else{
                this.form.provinceId=this.provinceId;
                this.popupShow=false;
                this.locationInfo=this.provinceName;
              }
           }else{
             this.$vux.toast.text('请选择省份', 'middel')
           }
         },
         cityTab(){
           if(this.cityList.length>0){
             this.locationIndex=1;
           }
         },
         countryTab(){
           if(this.countryList.length>0){
             this.locationIndex=2;
           }
         },
         townyTab(){
           if(this.townList.length>0){
             this.locationIndex=3;
           }
         },
         villageTab(){
           if(this.villageList.length>0){
             this.locationIndex=4;
           }
         },
         // 选择关系
         relationChange(val){
           this.form.relationship=val[0];
         },
       //  选择性别
         sexChange(val){
           if(val[0]=='男'){
              this.form.sex=0;
           }else{
             this.form.sex=1;
           }
         },
         submit(){
           let that=this;

          if(this.locationInfo==''){
            this.$vux.toast.text('请选择当前定位', 'middle')
          }else if(this.form.nowDetail==''){
            this.$vux.toast.text('请输入具体地址', 'middle')
          }else if(this.form.name==''){
            this.$vux.toast.text('请输入婴儿姓名', 'middle')
          }else if(this.form.motherName==''){
            this.$vux.toast.text('请输入妈妈姓名', 'middle')
          }else if(this.form.relationship==''){
            this.$vux.toast.text('请选择同儿童的关系', 'middle')
          }else if(this.form.sex==null){
            this.$vux.toast.text('请选择儿童的性别', 'middle')
          }else if(this.form.birthday==''){
            this.$vux.toast.text('请儿童的生日', 'middle')
          }else{
            let userId=sessionStorage.getItem('userId');

            that.formData.append('userId', String(userId));
            that.formData.append('birthday', String(this.form.birthday));
            that.formData.append('name', String(this.form.name));
            that.formData.append('relationship', String(this.form.relationship));
            that.formData.append('nowDetail', String(this.form.nowDetail));
            that.formData.append('provinceId', String(this.form.provinceId));
            that.formData.append('cityId', String(this.form.cityId));
            that.formData.append('countryId', String(this.form.countryId));
            that.formData.append('townId', String(this.form.townId));
            that.formData.append('villageId', String(this.form.villageId));
            that.formData.append('sex', String(this.form.sex));
            that.formData.append('serial', String(this.form.serial));
            that.formData.append('mother', String(this.form.motherName));
            that.formData.append('father', String(this.form.fatherName));

            let config = {
              headers: {
                'Content-Type': 'multipart/form-data'
              }
            }

            if(this.id){
              that.formData.append('id', String(this.id));
              this.$http.post(url.http_url+'/baby/updateBabyInfo', this.formData, config).then(function (res) {
                if(res.data.result==0){
                  that.$router.push({path: '/index'})
                }
              })
            }else{
              this.$http.post(url.http_url+'/baby/standardRegisterBaby', this.formData, config).then(function (res) {
                if(res.data.result==0){
                  that.$router.push({path: '/index'})
                }
              })
            }

          }

         },
         tirggerFile(event){
           let self = this;
           let file = event.target.files[0];
           this.formData.append('file', file);
           var reader = new FileReader();
           reader.readAsDataURL(file);
           reader.onload = function(e) {
             self.preImg=e.target.result
           }
         },
         reverseCity(){
           if(this.form.provinceId){
             this.$api.post('/systemPick/findAllCities',{
               type:'CITY',
               parentId:this.form.provinceId
             }).then( (res)=> {
               res.data.obj.forEach(item=>{
                 if(item.id==this.form.cityId){
                   this.cityName=item.name;
                   // this.cityId=item.id;
                   this.locationInfo=this.provinceName+' '+this.cityName;
                 }
               })
             })
           }


           if(this.form.cityId){
             this.$api.post('/systemPick/findAllCities',{
               type:'COUNTRY',
               parentId:this.form.cityId
             }).then( (res)=> {
               res.data.obj.forEach(item=>{
                 if(item.id==this.form.countryId){
                   this.countryName=item.name;
                   // this.countryId=item.id;
                   this.locationInfo=this.provinceName+' '+this.cityName+' '+this.countryName+' ';
                 }
               })
             })
           }

           if(this.form.countryId){
             this.$api.post('/systemPick/findAllCities',{
               type:'TOWN',
               parentId:this.form.countryId
             }).then( (res)=> {
               res.data.obj.forEach(item=>{
                 if(item.id==this.form.townId){
                   this.townName=item.name;
                   // this.townId=item.id;
                   this.locationInfo=this.provinceName+' '+this.cityName+' '+this.countryName+' '+this.townName;
                 }
               })
             })
           }

           if(this.form.townId){
             this.$api.post('/systemPick/findAllCities',{
               type:'VILLAGE',
               parentId:this.form.townId
             }).then( (res)=> {
               res.data.obj.forEach(item=>{
                 if(item.id==this.form.villageId){
                   this.villageName=item.name;
                   // this.townId=item.id;
                   this.locationInfo=this.provinceName+' '+this.cityName+' '+this.countryName+' '+this.townName+' '+this.villageName;
                 }
               })
             })
           }

         },
       },
        components: {
          XInput,
          XButton,
          PopupPicker,
          Datetime,
          Popup,
          TopBar
        }
    }
</script>

<style lang="scss">
    .add-wrapper{
      padding-top:10px;
      .address-con{
        background:rgba(255,255,255,1);
        box-shadow:-1px 0px 19px 2px rgba(50,51,51,0.06);
        border-radius:10px;
        margin:10px 15px 10px;
        padding:15px;
        .current-position{
          color:rgba(122,122,122,1);
          font-size:12px;
          font-family:PingFang-SC-Regular;
          margin:11px 0 6px;
        }
        .city{
          border-bottom: 1px solid #EEEEEE;
          height: 28px;
          line-height: 28px;
          font-size: 14px;
        }
        .details-address{
          .weui-cell{
            padding-left:0;
            .weui-input{
              color:rgba(38,38,38,1);
              font-size: 14px;
              padding-left:20px;
              &::-webkit-input-placeholder {
                color:rgba(173,173,173,1);
                font-size: 14px;
              }
            }
          }
        }
      }
      .title{
        font-size:15px;
        color:rgba(38,38,38,1);
        font-weight: normal;
        border-left:2px solid  #F56363;
        padding-left:4px;
      }
      .baby-info{
        background:rgba(255,255,255,1);
        box-shadow:-1px 0px 19px 2px rgba(50,51,51,0.06);
        border-radius:10px;
        margin:0 15px;
        padding:15px;
        .relation-select{
          border-bottom: 1px solid #EEEEEE;
          .vux-popup-picker-select{
            text-align: left!important;
            height: 36px;
            line-height: 36px;
            padding-left: 4px!important;
          }
          .weui-cell_access .weui-cell__ft:after{
            border-color:#C7C7C7;
            border-width: 1px 1px 0 0;
          }
          .vux-cell-placeholder{
            color:rgba(173,173,173,1);
            font-size: 14px;
          }
          .vux-cell-value{
            color:rgba(38,38,38,1);
            font-size: 14px;
          }
        }
        .datetime-select{
          border-bottom: 1px solid #EEEEEE;
          .weui-cell__ft{
            text-align: left!important;
            height: 36px;
            line-height: 36px;
            padding-left:4px!important;
          }
          .vux-cell-placeholder{
            color:rgba(173,173,173,1);
            font-size: 14px;
          }
          .vux-cell-value{
            color:rgba(38,38,38,1);
            font-size: 14px;
          }
          .weui-cell_access .weui-cell__ft:after{
            border-color:#C7C7C7;
            border-width: 1px 1px 0 0;
          }
        }
        .bar-code{
          border-bottom: 1px solid #EEEEEE;
          position: relative;
          .weui-input{
            color:rgba(38,38,38,1);
            font-size: 14px;
            padding-left:6px;
            &::-webkit-input-placeholder {
              color:rgba(173,173,173,1);
              font-size: 14px;
            }
          }
          .scan-btn{
            background:rgba(245,99,99,1);
            border-radius:10px;
            padding:0;
            width:74px;
            height:31px;
            line-height: 31px;
            font-size:14px;
            color:rgba(255,255,255,1);
            text-align: center;
          }
        }
        .upload-pic{
           margin-top:12px;
            .title{
              font-size:15px;
              color:rgba(38,38,38,1);
            }
            .upload-btn{
              border:1px solid rgba(210,210,210,1);
              width:70px;
              height:70px;
              text-align: center;
              margin-top: 9px;
              position: relative;
              background-size: 100% 100%;
              .upImg{
                position: absolute;
                top:0;
                right:0;
                width:70px;
                height:70px;
                opacity: 0;
              }
              a{
                font-size: 40px;
                color:#D2D2D2;
                font-weight: normal;
              }
              p{
                font-size:9px;
                color:rgba(199,199,199,1);
              }
            }
        }
      }
      .btn-wrapper{
        margin:40px 15px 40px;
        .weui-btn{
          background:rgba(245,99,99,1);
          border-radius:25px;
          color:rgba(255,255,255,1);
          font-size:17px;
        }
        .weui-btn_default:not(.weui-btn_disabled):active{
          background:rgba(245,99,99,1);
          color:rgba(255,255,255,1);
        }
        .weui-btn_disabled.weui-btn_default{
          opacity: 0.5;
        }
      }
    }
    .location-popup{
      background:#fff!important;
      overflow-y:hidden!important;
      .location-tab-nav{
        padding:10px;
        a{
          display: inline-block;
          width:auto;
          font-size: 14px;
          height: 30px;
          line-height: 30px;
          margin-right: 20px;
          &.active{
            border-bottom: 1px solid #f56363;
          }
        }
        .confirm-btn{
          color:red;
          float: right;
          margin-right:10px;
        }
      }
      .location-con{
        height: 300px;
        overflow-y: scroll;
        ul{
          li{
            font-size: 14px;
            height: 35px;
            line-height: 35px;
            border-bottom: 1px solid #EEEEEE;
            color: #262626;
            padding:0 10px;
            &.active{
              background: #eee;
            }
          }
        }
      }
    }
    .red-icon{
      color:red;
      position: absolute;
      top:12px;
      left:2px;
    }
  .details-address{
    position: relative;
  }
  .common-select{
    position: relative;
    .red-icon{
      top:22px;
    }
  }
  .red-icon-position{
    color:red;
    margin-right: 10px;
    font-size: 14px;
  }
</style>
